<template>
  <div class="score-prediction-container">
    <!-- 筛选区域 -->
    <el-card class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" :rules="rules">
        <el-form-item label="省份" prop="province">
          <el-select v-model="queryParams.province" filterable placeholder="请选择省份">
            <el-option v-for="item in provinces" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-input v-model="queryParams.school" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="queryParams.major" placeholder="请输入专业名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询分数线</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 历史数据图表 -->
    <el-card v-if="showChart" class="chart-container">
      <div class="chart-header">
        <h3>近5年高考分数线趋势</h3>
        <div class="chart-info">
          <span>学校：{{ queryParams.school }}</span>
          <span>专业：{{ queryParams.major }}</span>
        </div>
      </div>

      <!-- 添加图表类型切换的Tab -->
      <el-tabs v-model="chartType" @tab-click="handleChartTypeChange">
        <el-tab-pane label="曲线图" name="smooth"/>
        <el-tab-pane label="折线图" name="line"/>
        <el-tab-pane label="柱状图" name="bar"/>
      </el-tabs>

      <div ref="chartRef" class="chart-content"></div>
    </el-card>

    <!-- 分数预测部分 -->
    <el-card class="prediction-container">
      <div class="prediction-header">
        <h3>分数预测</h3>
        <p class="prediction-desc">根据近五年的分数线数据，预测今后三年该专业的录取分数线</p>
      </div>

      <!-- 添加五个输入框 -->
      <el-form ref="scoreForm" label-width="120px" :model="scoreParams" size="small">
        <el-row :gutter="20">
          <el-col
            v-for="(item, index) in 5"
            :key="index"
            :span="8"
          >
            <el-form-item
              :label="`${currentYear - 5 + item}年分数`"
              :prop="`year${index + 1}`"
              :rules="[
                { required: true, message: '请输入分数', trigger: 'blur' },
                { type: 'number', message: '分数必须为数字', trigger: 'blur' }
              ]"
            >
              <el-input-number
                v-model="scoreParams[`year${index + 1}`]"
                controls-position="right"
                :max="750"
                :min="0"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            :disabled="!canPredict"
            type="primary"
            @click="handlePredict"
          >预测分数</el-button>
          <el-button @click="resetScoreForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 预测结果展示区域 -->
      <div v-if="showResult" class="result-content">
        <el-divider content-position="center">预测结果</el-divider>
        <el-row :gutter="20">
          <el-col :offset="6" :span="12">
            <el-card shadow="hover">
              <div slot="header">
                <span>{{ queryParams.school }} - {{ queryParams.major }} 未来三年分数线预测</span>
              </div>
              <div class="prediction-results">
                <div v-for="(item, index) in predictionResults" :key="index" class="prediction-item">
                  <div class="prediction-year">{{ item.year }}年</div>
                  <div class="prediction-score">预测分数线：<span class="score-value">{{ item.score }}</span> 分</div>
                </div>
              </div>
              <div class="prediction-tips">
                <p>注意：预测结果仅供参考，实际分数线可能会受多种因素影响</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getSchoolLine, getPredict } from '@/api/purchase'
export default {
  name: 'ScorePrediction',
  data() {
    return {
      scoreParams: {
        year1: '',
        year2: '',
        year3: '',
        year4: '',
        year5: ''
      },
      currentYear: new Date().getFullYear(),
      chartType: 'smooth',
      // 查询参数
      queryParams: {
        province: '',
        school: '',
        major: ''
      },
      school: '',
      major: '',
      province: '',
      // 表单验证规则
      rules: {
        province: [{ required: true, message: '请选择省份', trigger: 'change' }],
        school: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
        major: [{ required: true, message: '请输入专业名称', trigger: 'blur' }]
      },
      // 省份列表
      provinces: [
        '北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙江',
        '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南',
        '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾',
        '内蒙古', '广西', '西藏', '宁夏', '新疆', '香港', '澳门'
      ],
      // 是否显示图表
      showChart: false,
      // 是否显示预测结果
      showResult: false,
      // 预测结果 - 修改为数组
      predictionResults: [],
      // 预测置信度 - 添加默认值
      confidence: 80, // 默认置信度，因为API不再提供
      // 图表实例
      chart: null,
      // 历史数据
      historyData: {
        years: [],
        scores: []
      }
    }
  },
    mounted() {
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    // 查询分数线
    async handleQuery() {
      this.$refs.queryForm.validate(async valid => {
        if (valid) {
          // 显示加载中
          const loading = this.$loading({
            lock: true,
            text: '正在查询历年分数线数据...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          try {
            // 获取近5年数据
            await this.fetchHistoryData();

            // 显示图表
            this.showChart = true;

            // 初始化图表
            this.$nextTick(() => {
              this.initChart();
            });
          } catch (error) {
            console.error('查询失败:', error);
            this.$message.error('查询失败，请稍后再试');
          } finally {
            // 关闭加载
            loading.close();
          }
        } else {
          this.$message.warning('请填写完整的查询条件');
          return false;
        }
      });
    },

    // 模拟获取历史数据
    async fetchHistoryData() {
      if (!this.queryParams.school || !this.queryParams.major || !this.queryParams.province) {
        console.log('school or major or province is empty', this.queryParams);
        this.$message.warning('请先在表单中选择学校、专业和省份');
        // 清空历史数据，避免显示旧数据
        this.historyData.years = [];
        this.historyData.scores = [];
        // 如果有图表实例，可能需要更新图表以显示空状态
        if (this.chart) {
          this.chart.setOption({
            xAxis: { data: [] },
            series: [{ data: [] }],
          });
        }
        return;
      }else{
        console.log('school or major or province is not empty', this.queryParams);
      }

      this.historyData.years = [];
      this.historyData.scores = [];

      console.log('开始获取历史分数线数据...', this.queryParams);

      try {
        // 确保所有参数都是字符串类型
        const params = {
          school: String(this.queryParams.school),
          special: String(this.queryParams.major),
          province: String(this.queryParams.province),
        };

        const response = await getSchoolLine(params);
        console.log('API返回的历史分数线数据:', response);

        // 检查响应中是否包含data数组
        if (response && response.data && Array.isArray(response.data)) {
          // 对数据按年份排序
          const scoreEntries = response.data.sort((a, b) => parseInt(a.Year) - parseInt(b.Year));

          if (scoreEntries.length === 0) {
            this.$message.info('未查询到该条件下的历史分数线数据');
          } else {
            scoreEntries.forEach(entry => {
              if (entry.Year && entry.MajorScore !== undefined && entry.MajorScore !== null) {
                this.historyData.years.push(String(entry.Year)); // 确保年份是字符串
                this.historyData.scores.push(Number(entry.MajorScore)); // 确保分数是数字
              }
            });

            // 显示图表
            this.showChart = true;
            // 初始化图表
            this.$nextTick(() => {
              this.initChart();
            });
          }
        } else {
          console.warn('API返回的历史分数线数据格式不正确或为空:', response);
          this.$message.info('未查询到相关历史分数线数据或数据格式不正确');
          // 确保图表清空
          if (this.chart) {
            this.chart.setOption({
              xAxis: { data: [] },
              series: [{ data: [] }],
            });
          }
        }
      } catch (error) {
        console.error('获取历史分数线数据失败:', error);
        this.$message.error('获取历史分数线数据失败，请稍后再试');
        // 出错时也清空数据
        this.historyData.years = [];
        this.historyData.scores = [];
      } finally {
        // 确保图表更新
      }
    },
    // 重置查询
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.showChart = false;
      this.showResult = false;
    },

    // 初始化图表
    initChart() {
if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.chartRef);

      // 根据当前选择的图表类型设置不同的配置
      let seriesType = 'line';
      let smooth = false;
      let areaStyle = null;

      if (this.chartType === 'smooth') {
        seriesType = 'line';
        smooth = true;
        areaStyle = {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        };
      } else if (this.chartType === 'line') {
        seriesType = 'line';
        smooth = false;
        areaStyle = null;
      } else if (this.chartType === 'bar') {
        seriesType = 'bar';
        smooth = false;
        areaStyle = null;
      }

      const option = {
        title: {
          text: `${this.queryParams.school} - ${this.queryParams.major} 历年分数线`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}年<br/>{a}: {c}分'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: this.chartType === 'bar', // 柱状图需要设置boundaryGap为true
          data: this.historyData.years,
          name: '年份',
          nameLocation: 'end',
          nameGap: 5
        },
        yAxis: {
          type: 'value',
          name: '分数',
          nameLocation: 'end',
          min: function(value) {
            return Math.floor(value.min - 20);
          }
        },
        series: [
          {
            name: '分数线',
            type: seriesType,
            data: this.historyData.scores,
            smooth: smooth,
            symbol: seriesType === 'line' ? 'circle' : 'none',
            symbolSize: seriesType === 'line' ? 8 : 0,
            itemStyle: {
              color: '#409EFF'
            },
            lineStyle: seriesType === 'line' ? {
              width: 3
            } : undefined,
            areaStyle: areaStyle,
            // 为柱状图添加特殊样式
            barWidth: seriesType === 'bar' ? '40%' : undefined,
            barMaxWidth: seriesType === 'bar' ? 50 : undefined,
            // 为柱状图添加标签
            label: seriesType === 'bar' ? {
              show: true,
              position: 'top',
              formatter: '{c}分'
            } : undefined
          }
        ]
      };

      this.chart.setOption(option);
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },

    // 判断是否可以进行预测
    canPredict() {
      return this.queryParams.school &&
             this.queryParams.major &&
             this.queryParams.province &&
             this.scoreParams.year1 !== null &&
             this.scoreParams.year2 !== null &&
             this.scoreParams.year3 !== null &&
             this.scoreParams.year4 !== null &&
             this.scoreParams.year5 !== null;
    },
    // 分数预测
    async handlePredict() {
      // 验证表单
      this.$refs.scoreForm.validate(async valid => {
        if (!valid) {
          this.$message.warning('请正确填写所有历年分数');
          return;
        }

        // 显示加载中
        const loading = this.$loading({
          lock: true,
          text: '正在进行分数预测...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        try {
          // 构建正确的请求参数结构
          const payload = {
            nums: [
              parseFloat(this.scoreParams.year1),
              parseFloat(this.scoreParams.year2),
              parseFloat(this.scoreParams.year3),
              parseFloat(this.scoreParams.year4),
              parseFloat(this.scoreParams.year5)
            ]
          };

          console.log('发送预测请求参数:', payload);
          const response = await getPredict(payload);
          console.log('预测API响应:', response);

          // 处理API返回的数据 - 根据新的结构调整
          if (response && response.predictions) {
            const predictions = response.predictions;
            const currentYear = new Date().getFullYear();
            this.predictionResults = [
              { year: currentYear + 1, score: predictions.step1 },
              { year: currentYear + 2, score: predictions.step2 },
              { year: currentYear + 3, score: predictions.step3 }
            ];

            this.showResult = true;
            this.$message.success('分数预测完成');
          } else {
            this.$message.error('预测失败，返回数据格式不正确或为空');
            this.predictionResults = []; // 清空结果
          }
        } catch (error) {
          console.error('预测分数失败:', error);
          this.$message.error('预测失败，请稍后再试');
          this.predictionResults = []; // 清空结果
        } finally {
          loading.close();
        }
      });
    },

    // 重置分数输入表单
    resetScoreForm() {
      this.$refs.scoreForm.resetFields();
      this.predictionResults = []; // 确保重置为数组
      this.showResult = false;
    },

    // 处理图表类型切换
    handleChartTypeChange() {
      // 重新初始化图表
      this.$nextTick(() => {
        this.initChart();
      });
    },
  },
}
</script>

<style lang="scss" scoped>
.score-prediction-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .chart-container {
    margin-bottom: 20px;

    .chart-header {
      margin-bottom: 20px;

      h3 {
        margin-bottom: 10px;
      }

      .chart-info {
        color: #606266;
        font-size: 14px;

        span {
          margin-right: 20px;
        }
      }
    }

    .chart-content {
      height: 400px;
    }
  }

  .prediction-container {
    .prediction-header {
      margin-bottom: 20px;

      h3 {
        margin-bottom: 10px;
      }

      .prediction-desc {
        color: #606266;
        font-size: 14px;
      }
    }

    .prediction-action {
      text-align: center;
      margin-bottom: 20px;
    }

    .result-content {
      margin-top: 20px;

      .prediction-score {
        font-size: 20px;
        text-align: center;
        padding: 20px 0;

        .score-value {
          font-size: 28px;
          color: #409EFF;
          font-weight: bold;
        }
      }

      .prediction-tips {
        color: #606266;
        font-size: 14px;
        text-align: center;

        p {
          margin: 5px 0;
        }
      }
    }
  }
}

.prediction-results {
  margin-bottom: 20px;
}

.prediction-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.prediction-year {
  font-weight: bold;
  margin-right: 20px;
  min-width: 60px;
}

.prediction-score {
  flex: 1;
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.prediction-tips {
  color: #909399;
  font-size: 14px;
}

.chart-container {
  margin-bottom: 20px;

  .chart-header {
    margin-bottom: 10px;

    h3 {
      margin-bottom: 10px;
    }

    .chart-info {
      color: #606266;
      font-size: 14px;

      span {
        margin-right: 20px;
      }
    }
  }

  .el-tabs {
    margin-bottom: 15px;
  }

  .chart-content {
    height: 400px;
  }
}
</style>
